import { useEffect, useState } from 'react';
import { Card, Button, Input, Modal, Form, message, Popconfirm, Row, Col, Typography, Tag, Menu, Select, Checkbox } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, BookOutlined } from '@ant-design/icons';
import { marketingStrategyApi } from '../lib/marketingStrategyApi';

const { TextArea } = Input;
const { Title, Text } = Typography;
const { Option } = Select;

interface CustomerProfile {
  name: string;
  description: string;
}

interface StrategyDetail {
  description: string;
  profile_description: CustomerProfile[];
  tragger_point: string;
}

interface MarketingStrategy {
  id: string | number;
  strategy_name: string;
  strategy_category: string;
  sop_stage: string;
  sop_node: string;
  strategy_detail: StrategyDetail;
  created_at?: string;
  updated_at?: string;
  created_by?: string;
  updated_by?: string;
}

const defaultForm = {
  strategy_name: '',
  strategy_category: '',
  sop_stage: '',
  sop_node: '',
  strategy_detail: {
    description: '',
    profile_description: [],
    tragger_point: ''
  }
};

// 预定义的策略分类选项
const strategyCategories = [
  '入金策略',
  '关系建立',
  '到账转换',
  '劣品转换',
  '单品加减仓赎回',
  '情绪安抚',
  '持仓配置',
  '推品策略',
  '收益解读',
  '赎回干预'
];

// 预定义的沟通阶段选项
const communicationStages = [
  '自我介绍阶段',
  '用户信息和偏好了解阶段',
  '理念塑造和市场解读阶段',
  '持仓诊断阶段',
  '资产配置阶段',
  '选品阶段',
  '服务后跟进阶段'
];

// 预定义的节点选项 - 根据沟通阶段动态变化
const nodeOptionsByStage: Record<string, string[]> = {
  '自我介绍阶段': [
    '自我介绍通过问候语',
    '进线发言承接',
    '表明来意-服务切入',
    '表明来意-持仓切入',
    '表明来意-市场切入',
    '表明来意-活动切入',
    '理财师服务内容介绍',
    '专业服务品牌介绍',
    '规划师服务内容介绍',
    '黑卡品牌和权益介绍',
    '活动规划介绍'
  ],
  '用户信息和偏好了解阶段': [
    '了解产品偏好',
    '了解行业偏好',
    '了解投资目标',
    '了解过往投资经验',
    '了解市场观点',
    '了解资金赎回原因',
    '了解后续资金安排',
    '了解个人和家庭情况',
    '了解资产收入情况'
  ],
  '理念塑造和市场解读阶段': [
    '选品理念',
    '资产配置理念',
    '保险配置理念',
    '金融基础术语解释',
    '投资行为或投资纪律',
    '市场行情或热点事件回顾',
    '市场展望观点和论据',
    '市场操作建议和论据',
    '广大类解读',
    '市场研判方法论'
  ],
  '持仓诊断阶段': [
    '投研品牌介绍',
    '持仓诊断 - 行为发现',
    '持仓诊断 - 问题发现',
    '持仓诊断 - 机会发现'
  ],
  '资产配置阶段': [
    '资产配置 - 配置方案内容',
    '资产配置 - 配置方案论据'
  ],
  '选品阶段': [
    '产品推荐 - 公募权益',
    '产品推荐 - 高端理财',
    '产品推荐 - 公募稳健',
    '产品推荐 - 通用',
    '选品诊断 - 品宣',
    '选品论据 - 市场、赛道分析及展望',
    '产品解读 - 投资目标 / 策略',
    '产品特色 / 亮点',
    '产品解读 - 历史表现',
    '产品解读 - 管理规模 / 管理人及机构信息',
    '产品解读 - 交易规则 / 费率',
    '产品解读 - 通用',
    '产品对比',
    '引导关联或提额'
  ],
  '服务后跟进阶段': [
    '确定后续待办',
    '确定后续沟通安排',
    '提示后续服务内容',
    '引导MGM',
    '引导完成合投'
  ]
};

// 预定义的客户标签选项
const customerTagOptions = [
  { 
    label: '年轻初级客户', 
    value: 'young_beginner',
    description: '<35岁，风险等级R2-R3，流动性偏好高，投资新手，AUM 小额/中额（<200万）'
  },
  { 
    label: '中年积累期客户', 
    value: 'middle_accumulation',
    description: '35-55岁，风险等级R2-R3，流动性偏好中低，中级投资经验，AUM 中额/高额（50-500万）'
  },
  { 
    label: '高净值中青年客户', 
    value: 'high_net_worth_young',
    description: '30-55岁，风险等级R3-R4，流动性偏好中高级，中高级投资经验，高净值>500万'
  },
  { 
    label: '稳健养老客户', 
    value: 'stable_retirement',
    description: '>55岁，风险等级R1-R2，流动性需求高，投资新手或中级投资经验，AUM 中额/高额（50-500万）'
  },
  { 
    label: '激进专业客户', 
    value: 'aggressive_professional',
    description: '30-50岁，风险等级R4-R5，流动性偏好中低，专业投资者，高净值>200万'
  }
];

const MarketingStrategyLibrary = () => {
  const [list, setList] = useState<MarketingStrategy[]>([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<MarketingStrategy | null>(null);
  const [selectedCategory, setSelectedCategory] = useState<string>('所有策略');
  const [selectedStage, setSelectedStage] = useState<string>(''); // 添加选中的阶段状态
  const [form] = Form.useForm();

  const fetchList = async () => {
    setLoading(true);
    try {
      const res = await marketingStrategyApi.getList(search);
      // 兼容后端返回 { strategies: [...] } 或直接数组
      let arr: any[] = [];
      if (res.success) {
        if (res.data && Array.isArray(res.data.strategies)) {
          arr = res.data.strategies;
        }
        setList(arr);
      } else {
        message.error(res.message || '获取营销策略失败');
        setList([]);
      }
    } catch (error) {
      message.error('获取营销策略失败');
      setList([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchList();
  }, [search]);

  const handleAdd = () => {
    setEditing(null);
    setSelectedStage(''); // 重置选中的阶段
    form.setFieldsValue(defaultForm);
    setModalOpen(true);
  };

  const handleEdit = (record: MarketingStrategy) => {
    setEditing(record);
    setSelectedStage(record.sop_stage || ''); // 设置选中的阶段
    
    // 将CustomerProfile[]转换为对应的value数组
    const profileValues = Array.isArray(record.strategy_detail.profile_description) 
      ? record.strategy_detail.profile_description.map(profile => {
          // 根据name找到对应的value
          const option = customerTagOptions.find(opt => opt.label === profile.name);
          return option ? option.value : profile.name;
        })
      : [];
    
    form.setFieldsValue({
      strategy_name: record.strategy_name,
      strategy_category: record.strategy_category,
      sop_stage: record.sop_stage || '',
      sop_node: record.sop_node || '',
      strategy_detail: {
        description: record.strategy_detail.description,
        profile_description: profileValues,
        tragger_point: record.strategy_detail.tragger_point || ''
      }
    });
    setModalOpen(true);
  };

  const handleDelete = async (id: string | number) => {
    try {
      const res = await marketingStrategyApi.delete(id);
      if (res.success) {
        message.success('删除成功');
        fetchList();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 将选中的value数组转换为CustomerProfile[]
      const profileDescriptions = Array.isArray(values.strategy_detail.profile_description)
        ? values.strategy_detail.profile_description.map((value: string) => {
            const option = customerTagOptions.find(opt => opt.value === value);
            return {
              name: option ? option.label : value,
              description: option ? option.description : value
            };
          })
        : [];
      
      const data = {
        strategy_name: values.strategy_name,
        strategy_category: values.strategy_category,
        sop_stage: values.sop_stage,
        sop_node: values.sop_node,
        strategy_detail: {
          description: values.strategy_detail.description,
          profile_description: profileDescriptions,
          tragger_point: values.strategy_detail.tragger_point
        }
      };

      if (editing) {
        const res = await marketingStrategyApi.update(editing.id, data);
        if (res.success) {
          message.success('更新成功');
          setModalOpen(false);
          fetchList();
        } else {
          message.error(res.message || '更新失败');
        }
      } else {
        const res = await marketingStrategyApi.create(data);
        if (res.success) {
          message.success('创建成功');
          setModalOpen(false);
          fetchList();
        } else {
          message.error(res.message || '创建失败');
        }
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleCancel = () => {
    setModalOpen(false);
    setEditing(null);
    setSelectedStage(''); // 重置选中的阶段
    form.resetFields();
  };

  // 处理阶段选择变化
  const handleStageChange = (value: string) => {
    setSelectedStage(value);
    // 清空节点选择
    form.setFieldsValue({
      sop_node: undefined
    });
  };

  // 获取当前阶段对应的节点选项
  const getCurrentNodeOptions = () => {
    return selectedStage ? nodeOptionsByStage[selectedStage] || [] : [];
  };

  // 保证list为数组类型，防御性处理
  const safeList = Array.isArray(list) ? list : [];

  // 获取所有分类
  const categories = ['所有策略', ...Array.from(new Set(safeList.map(item => item.strategy_category)))];

  // 根据分类过滤策略
  const filteredList = selectedCategory === '所有策略'
    ? safeList
    : safeList.filter(item => item.strategy_category === selectedCategory);

  // 获取分类统计
  const getCategoryCount = (category: string) => {
    if (category === '所有策略') return safeList.length;
    return safeList.filter(item => item.strategy_category === category).length;
  };

  return (
    <div className="marketing-strategy-library flex" style={{ height: '100%' }}>
      {/* 左侧分类菜单 */}
      <div className="w-64 bg-gray-50 border-r border-gray-200 p-4">
        <div className="mb-6">
          <Title level={4} className="!mb-4 text-gray-800">营销策略分类</Title>
        </div>
        <Menu
          mode="inline"
          selectedKeys={[selectedCategory]}
          className="bg-transparent border-none"
          items={categories.map(category => ({
            key: category,
            label: (
              <div className="flex justify-between items-center">
                <span>{category}</span>
                <Tag color="blue" className="ml-2">
                  {getCategoryCount(category)}
                </Tag>
              </div>
            ),
            onClick: () => setSelectedCategory(category)
          }))}
        />
      </div>

      {/* 右侧内容区 */}
      <div className="flex-1 flex flex-col">
        {/* 顶部操作区 */}
        <div className="mb-3 flex justify-between items-center px-6 py-4 bg-white border-b border-gray-200">
          <div>
            <Title level={3} className="!mb-2">{selectedCategory}</Title>
            <Text type="secondary" className="text-sm">
              共有 <span className="font-semibold text-blue-600">{filteredList.length}</span> 个营销策略
            </Text>
          </div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
            className="shadow-sm"
          >
            新建策略
          </Button>
        </div>

        {/* 搜索区域 */}
        <div className="mb-6 px-6">
          <Input
            placeholder="搜索营销策略名称或分类"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            prefix={<SearchOutlined />}
            allowClear
            className="max-w-md"
          />
        </div>

        {/* 卡片列表滚动区 */}
        <div className="flex-1 px-6 pb-6" style={{ overflowY: 'auto' }}>
          {loading ? (
            <div className="text-center py-12">
              <div className="animate-spin w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full mx-auto mb-4"></div>
              <Text className="text-gray-600">正在加载营销策略...</Text>
            </div>
          ) : filteredList.length === 0 ? (
            <div className="text-center py-12">
              <BookOutlined className="text-4xl text-gray-400 mb-4" />
              <Title level={4} className="!mb-2 text-gray-500">暂无营销策略</Title>
              <Text type="secondary">
                {selectedCategory === '所有策略' 
                  ? '点击"新建策略"按钮开始创建您的第一个营销策略'
                  : `当前分类"${selectedCategory}"下暂无策略`
                }
              </Text>
            </div>
          ) : (
            <Row gutter={[16, 16]}>
              {filteredList.map((strategy) => (
                <Col xs={24} sm={12} md={8} lg={8} xl={8} key={strategy.id}>
                  <Card
                    className="marketing-strategy-card hover:shadow-lg transition-all duration-300 flex flex-col"
                    size="small"
                    style={{
                      borderRadius: '12px',
                      background: 'linear-gradient(135deg, #ffffff 0%, #fafafa 100%)',
                      border: '1px solid #f0f0f0',
                      minHeight: 280,
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'space-between'
                    }}
                    actions={[
                      <Button
                        type="text"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(strategy)}
                        className="text-blue-500 hover:text-blue-700"
                      >
                        编辑
                      </Button>,
                      <Popconfirm
                        title="确定删除这个营销策略吗？"
                        onConfirm={() => handleDelete(strategy.id)}
                        okText="确定"
                        cancelText="取消"
                      >
                        <Button
                          type="text"
                          icon={<DeleteOutlined />}
                          className="text-red-500 hover:text-red-700"
                        >
                          删除
                        </Button>
                      </Popconfirm>
                    ]}
                  >
                    <div className="space-y-3 flex flex-col h-full">
                      {/* 卡片头部 */}
                      <div className="flex justify-between items-start">
                        <div className="flex-1 pr-4">
                          <div className="flex items-center gap-2 mb-2">
                            <Title level={5} className="!mb-0 text-gray-900 line-clamp-2">
                              {strategy.strategy_name}
                            </Title>
                          </div>
                          <div className="flex flex-wrap items-center gap-1 mb-2">
                            {strategy.sop_stage && (
                              <Tag color="green" className="mb-1 text-xs">
                                {strategy.sop_stage}
                              </Tag>
                            )}
                            {strategy.sop_node && (
                              <Tag color="orange" className="mb-1 text-xs">
                                {strategy.sop_node}
                              </Tag>
                            )}
                          </div>
                        </div>
                      </div>

                      {/* 策略描述 */}
                      <div className="mb-3" style={{ maxHeight: 80, overflowY: 'auto' }}>
                        <Text className="text-gray-600 text-sm leading-relaxed">
                          {strategy.strategy_detail.description}
                        </Text>
                      </div>

                      {/* 客户类型标签 - 直接显示 */}
                      <div className="flex flex-wrap gap-1 mb-3">
                        {Array.isArray(strategy.strategy_detail.profile_description) ?
                          strategy.strategy_detail.profile_description.map((profile, index) => (
                            <Tag key={index} color="purple" className="mb-1">
                              {profile.name}
                            </Tag>
                          )) : (
                            <Text className="text-gray-600 text-sm">
                              {strategy.strategy_detail.profile_description}
                            </Text>
                          )
                        }
                      </div>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          )}
        </div>
      </div>

      {/* 新建/编辑弹窗 */}
      <Modal
        title={editing ? "编辑营销策略" : "新建营销策略"}
        open={modalOpen}
        onOk={handleSubmit}
        onCancel={handleCancel}
        width={600}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          className="mt-4"
        >
          <Form.Item
            name="strategy_name"
            label="策略名称"
            rules={[
              { required: true, message: '请输入策略名称' },
              { max: 50, message: '策略名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入策略名称" maxLength={50} />
          </Form.Item>

          <Form.Item
            name="strategy_category"
            label="策略分类"
            rules={[
              { required: true, message: '请选择策略分类' }
            ]}
          >
            <Select placeholder="请选择策略分类" allowClear>
              {strategyCategories.map(category => (
                <Option key={category} value={category}>
                  {category}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <div className="mb-4">
            <Text strong className="text-gray-700 mb-2 block">沟通场景</Text>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="sop_stage"
                  label="沟通阶段"
                  rules={[
                    { required: true, message: '请选择沟通阶段' }
                  ]}
                >
                  <Select
                    placeholder="请选择阶段"
                    allowClear
                    onChange={handleStageChange}
                  >
                    {communicationStages.map(stage => (
                      <Option key={stage} value={stage}>
                        {stage}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="sop_node"
                  label="节点"
                  rules={[
                    { required: true, message: '请选择节点' }
                  ]}
                >
                  <Select
                    placeholder="请选择节点"
                    allowClear
                    disabled={!selectedStage}
                  >
                    {getCurrentNodeOptions().map((node: string) => (
                      <Option key={node} value={node}>
                        {node}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          </div>

          <Form.Item
            name={['strategy_detail', 'description']}
            label="策略描述"
            rules={[
              { required: true, message: '请输入策略描述' },
              { max: 500, message: '策略描述不能超过500个字符' }
            ]}
          >
            <TextArea
              rows={4}
              placeholder="请输入策略描述"
              maxLength={500}
              showCount
            />
          </Form.Item>

          <Form.Item
            name={['strategy_detail', 'tragger_point']}
            label="使用规则"
            rules={[
              { max: 300, message: '使用规则不能超过300个字符' }
            ]}
          >
            <TextArea
              rows={3}
              placeholder="请描述策略的使用规则"
              maxLength={300}
              showCount
            />
          </Form.Item>

          <Form.Item
            name={['strategy_detail', 'profile_description']}
            label="客户标签"
            rules={[
              { required: true, message: '请选择客户标签' }
            ]}
          >
            <Checkbox.Group>
              <div className="grid grid-cols-2 gap-2">
                {customerTagOptions.map(option => (
                  <Checkbox key={option.value} value={option.value}>
                    {option.label}
                  </Checkbox>
                ))}
              </div>
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MarketingStrategyLibrary; 